<script lang="ts" setup>
  import { ref } from 'vue';
  import notice from '@/assets/music/notice.mp3';
  import * as _ from '@usemathx/utils';
  import { Message } from '@arco-design/web-vue';

  const status = ref(_.getStorage('onNotification', false));
  const granted = ref(false);

  const handleToggle = async () => {
    if (!status.value) {
      if (!('Notification' in window)) {
        Message.error('当前浏览器不支持通知功能');
      } else {
        const permission = await Notification.requestPermission();
        if (permission === 'granted') {
          status.value = true;
        }
      }
    } else {
      status.value = false;
    }
    _.setStorage('onNotification', status.value);
  };

  _.listen('doNotification', (data: any) => {
    if (status.value) {
      const notice = new Notification('系统提醒', {
        body: data.message,
      });
      _.emit('playRingTone');
      setTimeout(() => {
        notice.close();
      }, 5000);
    }
  });

  new WebSocket('wss://admin.fitgreasy.com/websocket').addEventListener('message', (event) => {
    try {
      const message = JSON.parse(event.data);
      if (message.type === 'notice') {
        _.emit('doNotification', { message: message.data });
      }
    } catch (error) {
      console.error(error);
    }
  });
</script>

<template>
  <div @click="handleToggle">
    <icon-message v-if="status" />
    <icon-message-banned v-else />
  </div>
</template>
